package org.example;

import okhttp3.*;
import org.json.JSONObject;

import java.io.*;

class ImageProcessingSDK {
    public static final String API_KEY = "Your API_KEY";
    public static final String SECRET_KEY = "Your SECRET_KEY";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    /**
     * 图像动漫化
     * @param imagePath
     * @return base64编码的图片
     * @throws IOException
     */
    public static String imageProcess(String imagePath) throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, getRequestParameters(imagePath));
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/image-process/v1/selfie_anime?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String image = parseResponse(response);

        // 新图片路径
        String newFilePath = "Your FilePath";
        //Base64字符串转图片
        Base64Util.convertBase64StrToImage(image, newFilePath);
        return newFilePath;
    }

    /**
     * 图像清晰度增强
     * @param imagePath
     * @return base64编码的图片
     * @throws IOException
     */
    public static String imageEnhancement(String imagePath) throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, getRequestParameters(imagePath));
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/image-process/v1/image_definition_enhance?access_token=" + getAccessToken())
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String image = parseResponse(response);

        //新文件路径
        String newFilePath = "Your FilePath";
        //Base64字符串转图片
        Base64Util.convertBase64StrToImage(image, newFilePath);
        return newFilePath;
    }

    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    static String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }

    /**
     * 获取请求参数
     *
     * @return 请求参数
     */
    public static String getRequestParameters(String filePath) throws IOException {

        String imageToBase64Str = Base64Util.getFileContentAsBase64(filePath);
        String requestParameters = "image=" + imageToBase64Str;
        return requestParameters;
    }

    /**
     * 解析返回的response json字符串 获取image字段的值
     *
     * @param response
     * @return
     * @throws IOException
     */
    public static String parseResponse(Response response) throws IOException {
        String base64Str = response.body().string();
        JSONObject jsonObject = new JSONObject(base64Str);
        String imageStr = jsonObject.getString("image");
        return imageStr;
    }



}
